package ar.edu.itba.it.poo

class Polynomial(coefficients: List[Double]) extends (Double => Double) {

    def get(index: Int): Double = coefficients(index)

    override def apply(x: Double): Double = {
        var result: Double = 0
        for ((coef, index) <- coefficients.zipWithIndex) {
            result += coef * Math.pow(x, index)
        }
        return result
    }

    override def toString: String = {
        val result: StringBuilder = new StringBuilder()
        for ((coef, index) <- coefficients.zipWithIndex) {
            val exponent: String = if (coef > 0) "^" + index.toString else ""
            result.append(coef + "x" + exponent)
        }

        return result.toString
    }
}

object PolynomialTest extends Application {

    val p = new Polynomial(List(1, 0, 4))

    /* Crea el polinomio f(x) = 4x^2 + 1  */

    println(p(1)); // imprime 5.0
    println(p(2)); // imprime 17.0
    println(p(0)); // imprime 1.0
}